package book;

import constant.Constant;
import utils.AnalyzingBook;
import utils.ScannerSingLeton;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    public Book[] books;
    public int bookCount;
    public Scanner scanner;
    private static Library library;
    private AnalyzingBook analyzingBook = new AnalyzingBook();
    private Library(){
        //读
        loadBook();
        scanner = ScannerSingLeton.scannerget();
    }
    public static Library getLibrary(){
        if(library == null){
            library = new Library();
        }
        return library;
    }
    //用于查看书架上有多少书
    private void loadBook(){
        try {
            Book[] allbook = analyzingBook.loadObject(Constant.ALL_BOOK_FILE_NAME);
            books = new Book[Constant.CAPACITY];
            if(allbook == null){
                bookCount = 0;
            }else {
                int allBooklen = allbook.length;
                if (allBooklen > books.length) {
                    books = new Book[allBooklen];
                }
                for (int i = 0; i < allBooklen; i++) {
                    books[i] = allbook[i];
                }
                bookCount = allBooklen;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void storeBook(){
        try{
            analyzingBook.storeObject(books,Constant.ALL_BOOK_FILE_NAME);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    public void addBook(Book book){
        System.out.println("liabary的addBook方法被执行");
        if(bookCount >= books.length){
            if(bookCount >= books.length){
               /* int newCapacity = (int) (books.length * 1.5);
                books = Arrays.copyOf(books, newCapacity);*/
                return;
            }
        }
//        books[bookCount++] = book;
        books[bookCount] = book;
        Book lastbook = books[bookCount - 1];
        bookCount++;
        book.setBookId(lastbook.getBookId() + 1);
        storeBook();
        System.out.println("图书上架成功，名称是" + book.getTitle());
    }
    public void searchBaook(){

    }
    public void diaplayBook(){
        System.out.println("显示图书");
        loadBook();
        for(int i = 0 ; i < bookCount ; i++){
            System.out.println(books[i]);
        }
    }


    public void exit(){
        System.exit(0);
    }

    public Book searchById(int bookId) {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId){
                return book;
            }
        }
        return null;
    }

    public void updateBook(Book book) {
        int bookId = book.getBookId();
        int index = searchByIdReturnIndex(bookId);
        if(index == -1){
            System.out.println("没有想要的图书，此时ID为：" + bookId);
            return;
        }
        books[index] = book;
        storeBook();
        System.out.println("书籍已更新，文件已写入：");
        System.out.println(books[index]);
    }
    private int searchByIdReturnIndex(int bookId){
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId){
                return i;
            }
        }
        return -1;
    }

    public void removeBook(int bookId) {
        int index = searchByIdReturnIndex(bookId);
        if(index == -1){
            System.out.println("no result");
            return;
        }
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i+1];
        }
        bookCount--;
        books[bookCount] = null;
        storeBook();
    }

    public void borrowCount() {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书籍：" + book.getTitle() + "借阅了" + book.getBorrowCount() + "次！");
        }
    }

    public void generateBook(int k) {
        loadBook();
        Book[] tmp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }
        Arrays.sort(tmp);
        Book generateBooks[] = new Book[k];
        for (int i = 0; i < k; i++) {
            generateBooks[i] = tmp[i];
        }
        System.out.println("最受欢迎的书籍如下");
        for (int i = 0; i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("书籍ID：" + book.getBookId() + " 书名： " + book.getTitle() + " 作者："
                    + book.getAuthor() +" 借阅次数： " + book.getBorrowCount());
        }
    }

    public void checkInventoryStatus() {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String borrwed = "未借出";
            if(book.isBorrowed()){
               borrwed = "已借出";
            }
            System.out.println("书籍：" + book.getTitle() + "借阅状态： " + borrwed);
        }
    }

    public void checkAndRemoveOldBooks() {
        loadBook();
        long currentTimestamp = System.currentTimeMillis();
// 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
//获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();
// 计算两个⽇期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate,
                    currentDate);
            if(yearsBetween >= 1) {
                System.out.print("图书 " + book.getTitle() + " 已经上架超过⼀年，是否\n" +
                        "                        移除？ (y/n)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
//确认删除调⽤remove⽅法进⾏删除
                    removeBook(books[i].getBookId());
                    i--; // 因为后⾯的书已经向前移动，所以要重新检查当前索引位置
                    System.out.println("下架成功");
                }
                flg = true;
            }
        }
        if(!flg) {
            System.out.println("没有上架超过⼀年的图书！");
        }
        storeBook();
    }

    public void borrowedbook(int bookId) {
        loadBook();
        Book book = searchById(bookId);
        book.setBorrowed(true);
        book.incrementBorrowCount();
        storeBook();
    }

    public void returnBook(int bookId) {
        loadBook();
        Book book = searchById(bookId);
        book.setBorrowed(false);
        book.decreaseBorrowCount();
        storeBook();
    }
}
